import base64
import pickle

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from mall_web.apps.goods.models import SKU


# 一：购物车增删改查
class CartCreatView(APIView):
    # 1.购物车新增
    def perform_authentication(self, request):
        # 进入视图后调用视图方法先不进行用户验证
        pass

    def post(self, request):  # noqa
        sku_id = request.data.get("sku_id")
        count = request.data.get("count")
        selected = request.data.get("select", True)
        # 判断是否是登录用户
        try:
            user = request.user
        except:
            user = None
        if user is not None:
            # 用户登录操作,存redis
            redis_client = get_redis_connection("cart")
            redis_client.hset("cart_%s" % user.id, sku_id, count)
            if selected:
                # 更新集合数据  sku_id
                redis_client.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                # 删除
                redis_client.srem('cart_selected_%s' % user.id, sku_id)
            # 返回结果
            return Response({"count": count})
        else:
            # 用户未登录操作，框架首先会到接口处理逻辑中去，再到cookie操作中，再到到pickle base64操作，
            cart_cookie = request.COOKIES.get("cart_cookie")
            if cart_cookie:
                cart = pickle.loads(base64.b64decode(cart_cookie))
            else:
                cart = {}

            sku_dic = cart.get("sku_id")
            if sku_dic:
                count += int(sku_dic["count"])

            cart[sku_id] = {
                "count": count,
                "selected": selected
            }
            # 设置cookie，返回数据
            cart_cookie = base64.b64encode(pickle.dumps(cart)).decode()
            response = Response({
                "count": count
            })
            response.set_cookie("cart_cookie", cart_cookie, max_age=60 * 60 * 24 * 7)
            return response

    # 2.购物车查看
    def get(self, request):  # noqa
        # 判断是否是登录用户
        try:
            user = request.user
        except:
            user = None
        if user is not None:
            # 这个地方需要思考什么
            redis_client = get_redis_connection("cart")
            skus_dict = redis_client.hgetall("cart_%s" % user.id)
            skus_selected = redis_client.smembers("cart_selected_%s" % user.id)
            cart = {}
            for sku_id, count in skus_dict.items():
                cart[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in skus_selected
                }

        else:
            cart_cookie = request.COOKIES.get('cart_cookie', None)
            if cart_cookie:
                # 有cookie 解密cookie
                cart = pickle.loads(base64.b64decode(cart_cookie))
            else:
                cart = {}

        # 数据对象查询
        skus = SKU.objects.filter(id__in=cart.keys())
        # 添加返回属性
        for sku in skus:
            sku.count = cart[sku.id]['count']
            sku.selected = cart[sku.id]['selected']

        cart_data = [sku.cart_dict() for sku in skus]

        return Response(cart_data)

    # 3.购物车修改
    def put(self, request):  # noqa
        sku_id = request.data.get("sku_id")
        count = request.data.get("count")
        selected = request.data.get("selected")
        # 判断是否是登录用户
        try:
            user = request.user
        except:
            user = None
        if user is not None:
            # hash哈希 user_id {sku_id:count,sku_id1:count1}
            # set集合 user_id {sku_id,sku_id1}
            redis_client = get_redis_connection("cart")
            redis_client.hset("cart_%s" % user.id, sku_id, count)
            if selected:
                redis_client.sadd("cart_selected_%s" % user.id, sku_id)
            else:
                redis_client.srem("cart_selected_%s" % user.id, sku_id)

            return Response({
                "count": count,
                "selected": selected
            })

        # 操作redis，拿cookie操作
        cart_cookie = request.COOKIES.get("cart_cookie", None)

        if cart_cookie:
            cart = pickle.loads(base64.b64decode(cart_cookie))
        else:
            cart = {}
        # cookie中的数据长什么样子
        # {sku_id:{count:count,selected:True}}
        cart[sku_id] = {
            "count": count,
            "selected": selected
        }
        cart_cookie = base64.b64encode(pickle.dumps(cart)).decode()
        response = Response({
            "count": count,
            "selected": selected
        })
        response.set_cookie("cart_cookie", cart_cookie, max_age=60 * 60 * 42 * 7)
        return response

    # 4.购物删除
    def delete(self, request):  # noqa
        sku_id = request.data.get("sku_id")
        # 判断是否是登录用户
        try:
            user = request.user
        except:  # noqa
            user = None
        if user is not None:
            redis_client = get_redis_connection("cart")
            redis_client.hdel("cart_%s" % user.id, sku_id)
            redis_client.srem("cart_selected_%s" % user.id, sku_id)
            return Response({"message": "ok"})
        # 删除redis
        response = Response({"message": "ok"})
        cart_cookie = request.COOKIES.get("cart_cookie")
        if cart_cookie:
            cart = pickle.loads(base64.b64decode(cart_cookie))
            del cart[sku_id]
            cart_cookie = base64.b64encode(pickle.dumps(cart)).decode()
            response.set_cookie('cart_cookie',cart_cookie,max_age=60*60*24*7)
            return response


# 二.购物车全选
class CartSelectAllView(APIView):
    def perform_authentication(self, request):
        # 进入视图后调用视图方法先不进行用户验证
        pass

    def put(self,request): # noqa
        selected = request.data.get("selected")
        try:
            user = request.user
        except:  # noqa
            user = None
        if user is not None:
            redis_client = get_redis_connection("cart")
            skus_id = redis_client.hkeys("cart_%s" % user.id)
            if selected:
                redis_client.sadd("cart_selected_%s"%user.id,*skus_id)
            else:
                redis_client.srem("cart_selected_%s"%user.id,*skus_id)
            return Response({"message": "ok"})
        # 删除cookie
        cart_cookie = request.COOKIES.get("cart_cookie")
        response = Response({"message": "ok"})
        if cart_cookie:
            cart = pickle.loads(base64.b64decode(cart_cookie))
            for sku_id in cart.keys():
                cart[sku_id]["selected"] = selected
                cart_cookie = base64.b64encode(pickle.dumps(cart)).decode()
            response.set_cookie("cart_cookie",cart_cookie,max_age=60*60*24*7)
        return response



